package com.pet.gateway.filter;

import com.pet.gateway.config.AuthProperties;
import com.pet.gateway.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

import static com.pet.common.utils.RedisConstants.LOGIN_USER_KEY;
import static com.pet.common.utils.RedisConstants.LOGIN_USER_TTL;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final StringRedisTemplate stringRedisTemplate;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (isExclude(request.getPath().toString())) {
            // 无需拦截, 直接放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("Authorization");
        String userInfo;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            userInfo = claims.get("userId").toString();
            Integer userId = Integer.valueOf(userInfo);
            String tokenKey = LOGIN_USER_KEY + userId;
            String tokenCache = stringRedisTemplate.opsForValue().get(tokenKey);
            if (tokenCache == null || !tokenCache.equals(token)) {
                throw new RuntimeException("登录信息已过期");
            }
            stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.HOURS);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        ServerWebExchange exchangeWithUserInfo = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        return chain.filter(exchangeWithUserInfo);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, antPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
